<?php

namespace App\Service\User;

use App\Constants\ErrorCode;
use App\Helpers\AliyunUtil;
use App\Helpers\DateUtil;
use App\Helpers\Helper;
use App\Model\CloseFriend;
use App\Model\Moment;
use App\Model\Setting\SettingUserLevel;
use App\Model\UserProfile;
use App\Model\UserProfilePersonal;
use App\Model\UserSocialProfile;
use App\Model\UserTag;
use App\Service\BaseService;

/**
 * 用户列表基类
 */
class UserBaseService extends BaseService
{
    function packPhotos(&$list = [], $userIds = [])
    {
        $platform = $this->request->input('platform', 1);
        $imagesInfo = $this->getMomentPics($userIds);
        foreach ($list as &$item) {
            $item['moment_pics'] = array_merge($item['moment_pics'], $imagesInfo[$item['user_id']] ?? []);
        }
        return;
    }

    /**
     * 动态相册
     */
    function getMomentPics($userIds = [])
    {
        $where = [
            ['status', Moment::STATUS_OK],
            ['images', '<>', '']
        ];
        $moments = Moment::where($where)->whereIn('user_id', $userIds)->orderBy('id', 'desc')->select(['images', 'user_id'])->limit(1000)->get()->toArray();
        $images = [];
        foreach ($moments as $moment) {
            if (!isset($images[$moment['user_id']])) $images[$moment['user_id']] = [];
            if (count($images[$moment['user_id']]) >= 3) continue;
            $images[$moment['user_id']] = array_merge($images[$moment['user_id']], Moment::packMomentImages($moment['images'])['thumb_images']);
        }
        return $images ?? [];
    }

    /**
     * 主播列表元素
     */
    function buildHostItem($userProfile = [], $selfProfile = null, $imAccounts = [])
    {
        $userId = $userProfile['user_id'];
        $video = $userProfile['video'] ? json_decode($userProfile['video'], true) : [];
        $voice = $userProfile['voice'] ? json_decode($userProfile['voice'], true) : [];
        $dist = Helper::randFloat(0, 50);
        $city = Helper::buildCity($selfProfile->locate_city ?: $selfProfile->city);
        return [
            'user_id' => $userId,
            'avatar' => UserProfile::buildAvatar($userProfile['avatar'], 800),
            'nick_name' => $userProfile['nick_name'],
            'self_intro' => $userProfile['self_intro'],
            'im_account' => $imAccounts[$userId] ?? '',
            'gender' => $userProfile['gender'],
            'online_status' => $userProfile['online'],
            'age' => DateUtil::dateDiff($userProfile['birthday'], date('Y-m-d'), 'Y'),
            'city' => $city,
            'level' => SettingUserLevel::getUserLevel($userProfile),
            //身份
            'role' => $userProfile['role'],
            //是否优质
            'is_recommend' => $userProfile['host_cate'] == UserProfile::HOST_CATE_A ? 1 : 0,
            //距离
            'distance' => $dist . 'km',
            'distance_value' => $dist,
            //视频封面
            'video' => $video ? AliyunUtil::VOICE_HOST . $video['link'] : '',
            //真人认证
            'real_avatar' => $userProfile['avatar'] && $userProfile['avatar_vrfy'] ? 1 : 0,
            //实名
            'real_name' => 1,
            //是否VIP
            'is_vip' => 0,
            'voice' =>  empty($voice) || !isset($voice['link']) ? null : [
                'link' => AliyunUtil::VOICE_HOST . $voice['link'],
                'duration' => (int)$voice['duration'],
            ],
            'show_accost' => config('busi.show_accost_'.$this->appId,1),
        ];
    }

    /**
     * 用户列表元素
     */
    function buildUserItem($userProfile = [], $myUserId = 0, $imAccounts = [])
    {
        $userId = $userProfile['user_id'];
        $closeValue = CloseFriend::getCloseValue($myUserId, $userId);
        $age = DateUtil::dateDiff($userProfile['birthday'], date('Y-m-d'), 'Y');
        $voice = $userProfile['voice'] ? json_decode($userProfile['voice'], true) : [];
        return [
            'user_id' => $userId,
            'avatar' => UserProfile::buildAvatar($userProfile['avatar'], 200),
            'nick_name' => $userProfile['nick_name'],
            'self_intro' => $userProfile['self_intro'],
            'im_account' => $imAccounts[$userId] ?? '',
            'gender' => $userProfile['gender'],
            'online_status' => $userProfile['online'],
            'age' => $age >= 18 ? $age : 18,
            'city' => $userProfile['locate_city'] ?: $userProfile['city'],
            'level' => $userProfile['rich_value'] == 0 ? 0 : SettingUserLevel::getUserLevel($userProfile),
            //是否显示亲密度
            'show_close' => $closeValue > 0 ? 1 : 0,
            //是否显示视频按钮
            'show_video' => CloseFriend::checkLock($closeValue, 'video_call') ? 0 : 1,
            //亲密值
            'close_value' => $closeValue,
            'max_close_value' => 100,
            'online_time' => DateUtil::timeFromNow(strtotime($userProfile['updated_at'])),
            //真人认证
            'real_avatar' => $userProfile['avatar'] && $userProfile['avatar_vrfy'] ? 1 : 0,
            //是否VIP
            'is_vip' => 0,
            //体力
            'energy' => UserProfile::getEnergy($userId),
            'voice' =>   empty($voice) || !isset($voice['link']) ? null : [
                'link' => AliyunUtil::VOICE_HOST . $voice['link'],
                'duration' => (int)$voice['duration'],
            ],
            'show_accost' => config('busi.show_accost_'.$this->appId,1),
        ];
    }

    /**
     * 根据参数构造查询条件
     */
    function buildSelectWhere($todayActive = false)
    {
        $age = $this->request->input('age', '');
        $online = intval($this->request->input('online', '-1'));
        $where = [];
        if ($online == 1) {
            $where[] = $todayActive ? ['user_profile.updated_at', '>', date('Y-m-d')] : ['online', 1];
        }
        if ($age) {
            $age = explode(',', $age);
            if (isset($age[1]) && $age[1]) {
                $where[] = ['birthday', '>=', date('Y-m-d', strtotime('-' . ($age[1] * 365) . ' day'))];
            }
            if (isset($age[0]) && $age[0]) {
                $where[] = ['birthday', '<=', date('Y-m-d', strtotime('-' . ($age[0] * 365) . ' day'))];
            }
        }
        return $where;
    }

    /**
     * 标签
     */
    function packNewTags(&$list = [], $userIds = [], $listType = 'host')
    {
        $socialTags = UserSocialProfile::getBatchProfile($userIds, 'tag');
        foreach ($list as &$item) {
            if ('host' == $listType) {
                $item['tags'] = array_merge(
                    ["{$item['age']}岁"],
                    $socialTags[$item['user_id']] ?? []
                );
                $item['tags_personal'] = array_slice(UserTag::getTagNames($item['user_id']), 0, 5);
            } else {
                $item['tags'] = [];
                $item['level'] > 0 && $item['tags'][] = "财富Lv" . $item['level'];
//                $item['energy'] && $item['tags'][] = "体力" . $item['energy'];
                $item['tags'][] = $item['age'] . "岁";
//                $item['city'] && $item['tags'][] = $item['city'];
            }
        }
        return;
    }

    /**
     * 标签
     */
    function packTags(&$list = [], $userIds = [])
    {
        foreach ($list as &$item) {
            $item['tags'] = array_merge(
                ["{$item['age']}岁"],
                array_slice(UserTag::getTagNames($item['user_id']), 0, 4)
            );
        }
        return;
    }

    /**
     * 喜欢的标签
     */
    function packLoveTags(&$list = [], $userIds = [])
    {
        foreach ($list as &$item) {
            $item['love_tags'] = array_slice(UserTag::getTagNames($item['user_id'], UserTag::TYPE_LOVE), 0, 4);
        }
        return;
    }

    /**
     * 主播是否真人，实名认证
     */
    function checkHostVrfy($userId, $userProfile = null)
    {
        if (UserProfilePersonal::checkVerifing($userId)) {
            return ['errcode' => ErrorCode::ID_VRFYING, 'errmsg' => '你的实名信息正在审核中，请等待人工审核通过后再操作～'];
        }
        $isHost = UserProfile::checkRoleHost($userProfile->role);
        if (!$isHost) {
            return ['errcode' => ErrorCode::NO_ID_VRFY, 'errmsg' => '平台提倡真实交友，请先实名认证～'];
        }
        //非真人认证
        $selfIsVrfy = UserProfile::checkAvatarVrfied($userId, $userProfile);
        if (!$selfIsVrfy) {
            return ['errcode' => ErrorCode::REAL_AVATAR_NOT_VRFY, 'errmsg' => '平台提倡真实交友，请真人头像认证后再重试～'];
        }
        return ['errcode' => 0];
    }

    /**
     * 真人认证状态
     * @param $userId
     * @param $userProfile
     * @return array|int[]
     */
    function checkHostVrfyAvatar($userId, $userProfile = null)
    {
        //非真人认证
        $selfIsVrfy = UserProfile::checkAvatarVrfied($userId, $userProfile);
        if (!$selfIsVrfy) {
            return ['errcode' => ErrorCode::REAL_AVATAR_NOT_VRFY, 'errmsg' => '平台提倡真实交友，请真人头像认证后再重试～'];
        }

        return ['errcode' => 0];
    }

    function checkHostVrfyV2($userId, $userRegTime, $userProfile = null)
    {
        $newGirlTaskValid = config('act.new_girl_task_valid', '2023-03-12');

        log_info(__CLASS__."==newGirlTaskValid:{$newGirlTaskValid}==userRegTime:{$userRegTime}");

        if ($userRegTime < $newGirlTaskValid) {
            return $this->checkHostVrfy($userId, $userProfile);
        }

        return $this->checkHostVrfyAvatar($userId, $userProfile);
    }
}
